const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const { log } = require("console");
const { v4: uuidv4 } = require('uuid');

const app = express();
const server = http.createServer(app);

const io = new Server(server, {
  cors: {
    origin: "*", //配置跨域
  },
});

// 生成唯一 ID
const generateUniqueId = () => {
  return uuidv4();
};



// 监听连接事件
io.on('connection', (sock) => {
    log("连接成功...");
    const uniqueId = generateUniqueId();
      // log(uniqueId)
    // 向客户端发送连接成功的消息并传递唯一 ID
    sock.emit("connectionSuccess", uniqueId);
  
    // 监听加入房间的事件
    sock.on("joinRoom", (roomId) => {
      // 判断当前房间人数
      const roomClients = io.sockets.adapter.rooms.get(roomId); // 获取房间内所有客户端
      if (roomClients && roomClients.size >= 2) {
        // log("Room is full");
        io.to(roomId).emit("roomFull");
      }
  
      sock.join(roomId); // 加入房间
      log(roomId);
    });
    sock.on("callRemote", (roomId) => {
      // log("收到视频请求", roomId);
      io.to(roomId).emit("callRemote");
    });
    // 接收offer
    sock.on("acceptCall", (roomId) => {
      // log("接受通话");
      io.to(roomId).emit("acceptCall");
    });
    sock.on("sendOffer", ({ offer, roomId }) => {
      // log('收到offer')
      io.to(roomId).emit("sendOffer", offer);
    });
    // 接收answer
    sock.on("sendAnswer", ({ answer, roomId }) => {
      // log('收到answer:',answer);
      io.to(roomId).emit("sendAnswer", answer);
    });
    // 收到candidate信息
    sock.on("sendCandidate", ({ candidate, roomId }) => {
      // log(candidate)
      io.to(roomId).emit("sendCandidate", candidate);
    });
    // 挂断
    sock.on("hangUp", (roomId) => {
      // log("挂断");
      io.to(roomId).emit("hangUp");
    });
    // 发送消息
    sock.on("sendMessage", ({ message, roomId }) => {
      // log("收到消息");
      io.to(roomId).emit("sendMessage", message);
    });
});

// 启动服务器
server.listen(3000, () => {
  log('服务器启动成功');
});
